// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables

import 'dart:io';
import 'dart:ui' as ui;
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';

 
import 'package:permission_handler/permission_handler.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:qr_flutter/qr_flutter.dart';

import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGButton.dart';
import 'package:junyeyishu/widgets/QGNavigationBar.dart';

class QGInvitePage extends StatefulWidget {
  const QGInvitePage({super.key});
  @override
  State<QGInvitePage> createState() => _QGInvitePageState();
}

class _QGInvitePageState extends State<QGInvitePage> {
  var globalKey = GlobalKey();

  dynamic rule;
  dynamic list;
  dynamic total;

  dynamic code;
  dynamic url;

  @override
  void initState() {
    super.initState();

    Network.post(url_u_getInvitationRule).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }
      rule = res.data?["rule_content"] ?? "";
    });

    Network.post(url_u_getFriendsList).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }
      list = res.data["list"];
      total = res.data["allnums"];

      if (mounted) setState(() {});
    });

    Network.get(url_u_getMergedUserInfo).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }

      var userInfo = res.data["user_info"];

      //生成邀请码
      var uid = userInfo["id"] ?? "0";
      code = getInviteCode(int.parse(uid)); 
      url = "${Network.h5URL}?code=$code";


      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: Color(0xFFFFFFFF),
      body: Stack(
        children: [
          QGImage(asset: "yao_bg", width: 375.rpx),
        SingleChildScrollView(
          child: Column(
            children: [

              SizedBox(height: 60.rpx + max(20, kSafeTop)),
              buildHeader(),
              SizedBox(height: 20.rpx),
              buildRecord(),
              SizedBox(height: 10.rpx + kSafeBottom),
            ],
          ),
        ),
        Positioned(child: 
          buildTop()
        ),
      ]),
    );
  }

  buildTop() {
    return Container(
      // color: Color(0xFFFFFFFF),
      child: QGNavigationBar(
        title: "",
        rightItem: GestureDetector(
          onTap: onRule,
          child: Container(
            // padding: EdgeInsets.only(
            //     top: 7.rpx, bottom: 7.rpx, left: 14.rpx, right: 11.rpx),
            // decoration: BoxDecoration(
            //   borderRadius: BorderRadius.only(
            //     topLeft: Radius.circular(20.rpx),
            //     bottomLeft: Radius.circular(20.rpx),
            //   ),
            //   color: Color(0xFFFFFFFF),
            // ),
            // child: Text(
            //   '邀请规则',
            //   style: TextStyle(
            //       color: Color(0xFF111111),
            //       fontSize: 11.rpx,
            //       fontWeight: FontWeight.normal),
            // ),
          ),
        ),
      ),
    );
  }

  buildHeader() {
    return RepaintBoundary(
      key: globalKey,
      child: Container(
        child: Stack(
          alignment: Alignment.center,
          children: [
            Container(//yaoqingma linajie xiazai
              height: 250.rpx,
              width: 345.rpx,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.rpx),
                color: Color(0XFF232A32)
              ),
              child: Column(
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 30.rpx),
                      width: 300,
                  alignment: Alignment.topLeft,
                    child:QGImage(asset: "yaoqingma", width: 80.rpx),
                  ),
                     Container(
                    margin: EdgeInsets.only(top: 15.rpx),

                      width: 300,
                      child: 
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                          Container(
                            alignment: Alignment.center,
                            height: 50,
                            width: 210,
                            decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(109.rpx),
                            color: Color(0XFF192126)
                          ),
                          child: Text(code ?? "",style: TextStyle(fontSize: 35,color: Color(0XFFFFFFFF),fontWeight: FontWeight.bold)),
                         ),
              GestureDetector(
                onTap: (){
                  onCopy1(code?? "");
                },
                child:Container(
                            alignment: Alignment.center,
                            height: 50,
                            width: 80,
                            decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(109.rpx),
                            color: Color(0XFF111111),
                          ),
                          child:Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                           QGImage(asset: "mine_copy_address", width:20.rpx),
                            ],
                          )
                         ),
              )
                          
                      ],
                    ),
                    ),
                    
                     Container(
                    margin: EdgeInsets.only(top: 30.rpx),

                      width: 300,

                      child: 
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                         Container(
                            height: 70,
                            width: 150,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                            borderRadius:BorderRadius.only(topLeft: Radius.circular(35),
                              bottomLeft: Radius.circular(35)
                            ),
                            color: Color(0XFF111111),
                          ),
                          child: 
                          GestureDetector(
                            onTap: (){
                              onCopy();
                            },
                            child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                                QGImage(asset: "linajie", width:20.rpx),
                                SizedBox(width: 10.rpx,),
                                Text('复制链接',style: TextStyle(fontSize: 16,color: Color(0XFFFFFFFF))),
                            ],
                          ),
                          )
                          
                          
                         ),
                         GestureDetector(
                          onTap: (){
                            onSave();
                          },
                          child: Container(
                            width: 150,
                            alignment: Alignment.center,

                            height: 70,
                            decoration: BoxDecoration(
                              borderRadius:BorderRadius.only(topRight: Radius.circular(35),
                              bottomRight: Radius.circular(35)
                            ),
                            color: Color(0XFFFFFFFF),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                                QGImage(asset: "xiazai", width:20.rpx),
                                SizedBox(width: 10.rpx,),
                                Text('保存图片',style: TextStyle(fontSize: 16,color: Color(0XFF111111))),
                            ],
                          )
                         ),
                         )
                        ,
                      ],
                    )
                     )
                    
                ],
              )
            )
,
        
            // Column(children: [
             
            //   Container(
            //     width: 130.rpx,
            //     decoration: BoxDecoration(
            //       borderRadius: BorderRadius.circular(6.rpx),
            //       color: Colors.white,
            //     ),
            //     padding: EdgeInsets.all(10.rpx),
            //     alignment: Alignment.center,
            //     child:
                  
            //         Transform.translate(
            //       offset: Offset(-1.rpx, 0.0),
            //       child: QrImageView(
            //         padding: EdgeInsets.zero,
            //         data: url ?? "",
            //         size: 110.rpx,
            //       ),
            //     ),
            //   ),
            //   SizedBox(height: 30.rpx),
            //   buildBottom(),
            // ]),
         
          ],
        ),
      ),
    );
  }

  buildRecord() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 10.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Color(0xFF232A32),
      ),
      child: Column(children: [
        SizedBox(height: 18.rpx),
        buildContentTitle("我的邀请好友列表"),
        Text(
          '有效邀请：完成实名、开通钱包、',
          style: TextStyle(
              color:Color(0XFF989EA4),
              fontSize: 14.rpx,
              fontWeight: FontWeight.normal),
        ),
        Text(
          ' 完成首次消费下单（含一级或二级买入订单）',
          style: TextStyle(
              color:Color(0XFF989EA4),
              fontSize: 14.rpx,
              fontWeight: FontWeight.normal),
        ),
        Text(
          '我已邀请 ${total ?? ""} 人',
          style: TextStyle(
              color: Color(0XFFFFFFFF),
              fontSize: 14.rpx,
              fontWeight: FontWeight.normal),
        ),
        Stack(
          children: [
            Column(
              children: [
                SizedBox(height: 25.rpx),

                  if(list!=null)
                for (var item in list)
                    Container(
      decoration: BoxDecoration(
      color: Color(0XFF0C1012),
      borderRadius: BorderRadius.circular(10)
      ),
      margin: EdgeInsets.symmetric(horizontal: 15.rpx,vertical: 7),
      padding: EdgeInsets.symmetric(horizontal: 20.rpx,vertical: 10.rpx),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
              crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('${item['phone']}',style: TextStyle(fontSize: 14,color: Color(0XFFFFFFFF)),),
              SizedBox(height: 5.rpx,),
              Text( '${item['created']}',style: TextStyle(fontSize: 12,color: Color(0XFF989EA4)),),

            ],
          ),
          Text(
          item['isValid']==1?'已实名':'未实名',style: TextStyle(fontSize: 14,color: Color(item['isValid']==1?0xff4AE3FF:0XFF989EA4)),),
        ],
      )

    ),

          // buildRecordCell(),

                ...buildEmpty(),


              ],
            ),
          ],
        ),
      ]),
    );
  }

  buildEmpty() {
    if (list is List && list.length > 0) {
      return [Container()];
    }

    return [
      Text(
        '暂无数据',
        style: TextStyle(
            color: Color(0XFFFFFFFF),
            fontSize: 12.rpx,
            fontWeight: FontWeight.normal),
      ),
      SizedBox(height: 20.rpx),
    ];
  }

  buildCellItem(content, {fontSize, alpha = 0.8}) {
    return Container(
      height: 18.rpx,
      child: Text(
        content,
        style: TextStyle(
            color: Color(0XFFFFFFFF),
            fontSize: fontSize ?? 14.rpx,
            fontWeight: FontWeight.normal),
      ),
    );
  }
    buildCellItem1(content, {fontSize, alpha = 0.8}) {
    return Container(
      height: 18.rpx,
      child: Text(
        content,
        style: TextStyle(
            color: Color(0XFF989EA4),
            fontSize: fontSize ?? 10.rpx,
            fontWeight: FontWeight.normal),
      ),
    );
  }

  buildCellItemState(content, {fontSize, rgb}) {
    return Container(
      child: Text(
        content,
        style: TextStyle(
            color: Color(rgb), fontSize: 14.rpx, fontWeight: FontWeight.normal),
      ),
    );
  }

   buildRecordCell() {
    list ??= [];

    var noList = [];
    var phoneList = [];
    var stateList = [];
    var created=[];
    
    for (var item in list) {
      bool check = item["isValid"] == 1;
      var state = check ? "已实名" : "未实名";
      var rgb = check ? 0xFF4AE3FF : 0xff999999;

      created.add(buildCellItem1(item?["created"].toString()));
      noList.add(buildCellItem(item?["no"].toString()));
      phoneList.add(buildCellItem(item["phone"] ?? ""));
      stateList.add(buildCellItemState(state, rgb: rgb));

    }

    return Container(
      decoration: BoxDecoration(
      color: Color(0XFF0C1012),
      borderRadius: BorderRadius.circular(10)
      ),
      margin: EdgeInsets.symmetric(horizontal: 15.rpx,vertical: 15),
      padding: EdgeInsets.symmetric(horizontal: 20.rpx,vertical: 10.rpx),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
              crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ...phoneList,
              SizedBox(height: 5.rpx,),
              ...created
            ],
          ),
            ...stateList

        ],
      )

    );
  }



  buildRecordCell1() {
    list ??= [];

    var noList = [];
    var phoneList = [];
    var stateList = [];
    var created=[];
    for (var item in list) {
      bool check = item["isValid"] == 1;
      var state = check ? "已实名" : "未实名";
      var rgb = check ? 0xFF4AE3FF : 0xff999999;

      created.add(buildCellItem1(item?["created"].toString()));

      noList.add(buildCellItem(item?["no"].toString()));
      phoneList.add(buildCellItem(item["phone"] ?? ""));
      stateList.add(buildCellItemState(state, rgb: rgb));


    }

    return Container(
      decoration: BoxDecoration(
      color: Color(0XFF0C1012),
      borderRadius: BorderRadius.circular(10)
      ),
      margin: EdgeInsets.symmetric(horizontal: 15.rpx,vertical: 15),
      padding: EdgeInsets.symmetric(horizontal: 20.rpx,vertical: 10.rpx),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
              crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ...phoneList,
              SizedBox(height: 5.rpx,),
              ...created
            ],
          ),
            ...stateList

        ],
      )

      // Stack(
      //   children: [
      //     Row(
      //       children: [
      //         Expanded(
      //           child: Column(
      //             crossAxisAlignment: CrossAxisAlignment.start,
      //             children: [
      //               Column(
      //                 crossAxisAlignment: CrossAxisAlignment.center,
      //                 children: [
      //                   // buildCellItem("编号", fontSize: 12.0.rpx, alpha: 1.0),
      //                   // SizedBox(height: 15.rpx),
      //                   ...noList
      //                 ],
      //               ),
      //             ],
      //           ),
      //         ),
      //         Expanded(
      //           child: Column(
      //             children: [
      //               // buildCellItem("用户手机", fontSize: 12.0.rpx, alpha: 1.0),
      //               // SizedBox(height: 15.rpx),
      //               ...phoneList
      //             ],
      //           ),
      //         ),
      //         Expanded(
      //           child: Column(
      //             crossAxisAlignment: CrossAxisAlignment.end,
      //             children: [
      //               Column(
      //                 children: [
      //                   // buildCellItem("邀请结果", fontSize: 12.0.rpx, alpha: 1.0),
      //                   // SizedBox(height: 15.rpx),
      //                   ...stateList
      //                 ],
      //               ),
      //             ],
      //           ),
      //         ),
      //       ],
      //     ),
       
      //   ],
      // ),
    );
  }

  buildContentTitle(title) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(width: 7.rpx),
        Flexible(
          child: Text(
            title ?? "",
            style: TextStyle(
                color: Color(0xFFFFFFFF),
                fontSize: 20.rpx,
                fontWeight: FontWeight.bold),
          ),
        ),
        SizedBox(width: 7.rpx),
      ],
    );
  }

  buildBottom() {
    return Row(
      children: [
        Expanded(
          child: GestureDetector(
            onTap: onCopy,
            child: Column(
              children: [
                QGImage(asset: "invite_copy"),
                SizedBox(height: 7.rpx),
                Text(
                  '复制链接',
                  style: TextStyle(
                      color: Color(0xFF111111),
                      fontSize: 12.rpx,
                      fontWeight: FontWeight.normal),
                ),
              ],
            ),
          ),
        ),
        Expanded(
          child: GestureDetector(
            onTap: onSave,
            child: Column(
              children: [
                QGImage(asset: "invite_save"),
                SizedBox(height: 7.rpx),
                Text(
                  '保存图片',
                  style: TextStyle(
                      color: Color(0xFF111111),
                      fontSize: 12.rpx,
                      fontWeight: FontWeight.normal),
                ),
              ],
            ),
          ),
        )
      ],
    );
  }

  onRule() {
    Navigator.of(context).pushNamed(PageRule,
        arguments: {"title": "邀请规则", "content": "$rule", "web": "1"});
  }

  onCopy() {
    Clipboard.setData(ClipboardData(text: url));
    toast("复制成功");
  }
   onCopy1(url) {
    Clipboard.setData(ClipboardData(text: url));
    toast("复制成功");
  }

  onSave() async {
    RenderRepaintBoundary? boundary =
        globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
    var image = await boundary?.toImage(pixelRatio: ui.window.devicePixelRatio);
    var byteData = await image?.toByteData(format: ui.ImageByteFormat.png);
    Uint8List? pngBytes = byteData?.buffer.asUint8List();

    if (pngBytes == null) {
      toast("生成图片失败");
      return;
    }
    if (!kIsWeb){
      if (Platform.isIOS) {
            if (!await Permission.photos.status.isGranted) {
              await Permission.photos.request();
            }
          } else if (Platform.isAndroid) {
            if (!await Permission.storage.status.isGranted) {
              await Permission.storage.request();
            }
          }
    }
    

    var ret = await ImageGallerySaverPlus.saveImage(pngBytes);
    if (ret["isSuccess"]) {
      toast("保存成功");
    } else {
      toast("保存失败,请检查相册权限");
    }
  }
}
